<template>
    <el-card shadow="never">
        <template #header>
            <div class="flex justify-between">
                <span class="text-sm">活跃学员统计</span>
                <div>
                    <el-check-tag v-for="(item, index) in options" :key="index" :checked="current == item.value"
                        style="margin-right: 8px" @click="handleChoose(item.value)">{{ item.text }}</el-check-tag>
                </div>
            </div>
        </template>
        <div ref="el" id="chart" style="width: 100%;height: 300px;"></div>
    </el-card>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { useResizeObserver } from '@vueuse/core'

import request from "~/utils/request.js";



const current = ref("week")

const handleChoose = (type) => {
    current.value = type
    getData()
}

var myChart = null
onMounted(() => {
    var chartDom = document.getElementById('chart');
    myChart = echarts.init(chartDom);

    getData()
})

onBeforeUnmount(() => {
    if (myChart) echarts.dispose(myChart)
})

async function getData() {
    let option = {
        xAxis: {
            type: 'category',
            data: [],
            name: '班级',
        },
        yAxis: {
            type: 'value',
            name: '学员人数',
            axisLabel: {
                formatter: '{value}'
            },
            min: 0,
            interval: null, // 自动计算刻度间隔
            boundaryGap: [0, 0.1]
        },
        series: [
            {
                data: [],
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                },
                label: {
                show: true,
                position: 'top'
            }
            }
        ]
    };
    myChart.showLoading();

    try {
        const res = await request.get('/train-class/findActiveClassAndStudent', {});

        if (res.code === '200') {
            option.xAxis.data = res.data.classInfo || [];
            option.series[0].data = res.data.value || [];

            const maxValue = Math.max(...option.series[0].data);
            const yMax = Math.ceil(maxValue * 1.2);
            option.yAxis.max = yMax;

        }
    } catch (error) {
        console.error('请求出错:', error);
    } finally {
        myChart.setOption(option);
        myChart.hideLoading();
    }
}


const el = ref(null)
useResizeObserver(el, (entries) => myChart.resize())

</script>
